<?php

namespace Admin\Model;

use Think\Model;

/** Description:
 * @Author: Tudo<997470395@qq.com>
 * @Created: 2015-2-16 下午12:49:59 */
class TagModel extends Model
{
	/** 批量插入tags** */
	public function insertTags($tags, $bid) {
		$tag_ids = array();
		foreach ( $tags as $k => $v ) {
			$bool = $this->_isTag( $v );
			if ($bool>0) {
				$tag_ids[]=$bool;
			}else{
				if($this->add(array('tag_name'=>$v,'sort'=>100))){
					$tid = $this->getLastInsID();
					$tag_ids[] =$tag_ids;
				};
			}
		}
		
		if ($this->_isHasTag( $bid )) {
			$this->table( 'blog_tag_relation' )->where( array('blog' => $bid) )->delete();
		}
		if (is_string( $tag_ids )) {
			return M( 'BlogTagRelation' )->add( array('tag_id' => $tags,'blog_id' => $bid) );
		}
		
		if (is_array( $tag_ids )&&!empty($tag_ids)) {
			
			foreach ( $tag_ids as $k => $v ) {
				$data[$k]['tag_id'] = $v;
				$data[$k]['blog_id'] = $bid;
			}
			
			return M( 'BlogTagRelation' )->addAll( $data );
		}
		return false;
	}
	/** 判断文章是否已经存在tag** */
	private function _isHasTag($bid) {
		$count = M( 'BlogTagRelation' )->where( array('blog_id' => $bid) )->count();
		return $count > 0;
	}
	/** 判断tag是否存在** */
	private function _isTag($tag) {
		$result = $this->where( array('tag_name' => $tag) )->field( 'id' )->find();
		if ($result['id']>0) return $result['id'];
		
		return 0;
	}
}